package com.zenithmind.document.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.document.pojo.domain.DocumentCategory;
import com.zenithmind.document.pojo.vo.DocumentCategoryVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 文档分类Mapper接口
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Mapper
public interface DocumentCategoryMapper extends BaseMapper<DocumentCategory> {

    /**
     * 分页查询分类（包含关联信息）
     * 
     * @param page 分页参数
     * @param keyword 关键词
     * @param parentId 父分类ID
     * @param status 状态
     * @return 分页结果
     */
    IPage<DocumentCategoryVO> selectCategoryPageWithDetails(Page<DocumentCategoryVO> page,
                                                           @Param("keyword") String keyword,
                                                           @Param("parentId") String parentId,
                                                           @Param("status") Integer status);

    /**
     * 获取分类树
     * 
     * @param parentId 父分类ID
     * @param includeDisabled 是否包含禁用的分类
     * @return 分类树
     */
    List<DocumentCategoryVO> selectCategoryTree(@Param("parentId") String parentId,
                                               @Param("includeDisabled") Boolean includeDisabled);

    /**
     * 获取子分类列表
     * 
     * @param parentId 父分类ID
     * @param includeDisabled 是否包含禁用的分类
     * @return 子分类列表
     */
    @Select("SELECT c.*, u.real_name as creator_name " +
            "FROM document_category c " +
            "LEFT JOIN user u ON c.creator_id = u.id " +
            "WHERE c.parent_id = #{parentId} AND c.deleted = 0 " +
            "AND (#{includeDisabled} = true OR c.status = 1) " +
            "ORDER BY c.sort_order ASC, c.create_time ASC")
    List<DocumentCategoryVO> selectChildCategories(@Param("parentId") String parentId,
                                                  @Param("includeDisabled") Boolean includeDisabled);

    /**
     * 获取分类路径
     * 
     * @param categoryId 分类ID
     * @return 分类路径
     */
    List<DocumentCategoryVO> selectCategoryPath(@Param("categoryId") String categoryId);

    /**
     * 检查分类名称是否存在
     * 
     * @param name 分类名称
     * @param parentId 父分类ID
     * @param excludeId 排除的分类ID
     * @return 是否存在
     */
    @Select("SELECT COUNT(*) > 0 FROM document_category " +
            "WHERE name = #{name} AND parent_id = #{parentId} " +
            "AND deleted = 0 " +
            "AND (#{excludeId} IS NULL OR id != #{excludeId})")
    Boolean checkCategoryNameExists(@Param("name") String name,
                                   @Param("parentId") String parentId,
                                   @Param("excludeId") String excludeId);

    /**
     * 更新分类文档数量
     * 
     * @param categoryId 分类ID
     * @return 影响行数
     */
    @Update("UPDATE document_category SET " +
            "document_count = (SELECT COUNT(*) FROM document WHERE category_id = #{categoryId} AND deleted = 0), " +
            "update_time = NOW() " +
            "WHERE id = #{categoryId}")
    int updateCategoryDocumentCount(@Param("categoryId") String categoryId);

    /**
     * 批量更新分类文档数量
     * 
     * @param categoryIds 分类ID列表
     * @return 影响行数
     */
    int batchUpdateCategoryDocumentCount(@Param("categoryIds") List<String> categoryIds);

    /**
     * 获取最大排序值
     * 
     * @param parentId 父分类ID
     * @return 最大排序值
     */
    @Select("SELECT COALESCE(MAX(sort_order), 0) FROM document_category " +
            "WHERE parent_id = #{parentId} AND deleted = 0")
    Integer getMaxSortOrder(@Param("parentId") String parentId);

    /**
     * 调整分类排序
     * 
     * @param categoryIds 分类ID列表（按新顺序排列）
     * @param parentId 父分类ID
     * @return 影响行数
     */
    int batchUpdateCategoryOrder(@Param("categoryIds") List<String> categoryIds,
                                @Param("parentId") String parentId);

    /**
     * 移动分类
     * 
     * @param categoryId 分类ID
     * @param newParentId 新父分类ID
     * @param newLevel 新层级
     * @param newPath 新路径
     * @return 影响行数
     */
    @Update("UPDATE document_category SET " +
            "parent_id = #{newParentId}, " +
            "level = #{newLevel}, " +
            "path = #{newPath}, " +
            "update_time = NOW() " +
            "WHERE id = #{categoryId}")
    int moveCategory(@Param("categoryId") String categoryId,
                    @Param("newParentId") String newParentId,
                    @Param("newLevel") Integer newLevel,
                    @Param("newPath") String newPath);

    /**
     * 复制分类
     * 
     * @param sourceCategoryId 源分类ID
     * @param newName 新分类名称
     * @param parentId 父分类ID
     * @param creatorId 创建者ID
     * @return 新分类ID
     */
    String copyCategory(@Param("sourceCategoryId") String sourceCategoryId,
                       @Param("newName") String newName,
                       @Param("parentId") String parentId,
                       @Param("creatorId") String creatorId);

    /**
     * 获取分类统计信息
     * 
     * @param categoryId 分类ID
     * @return 统计信息
     */
    DocumentCategoryVO selectCategoryStatistics(@Param("categoryId") String categoryId);

    /**
     * 搜索分类
     * 
     * @param keyword 关键词
     * @param limit 限制数量
     * @return 分类列表
     */
    @Select("SELECT c.*, u.real_name as creator_name " +
            "FROM document_category c " +
            "LEFT JOIN user u ON c.creator_id = u.id " +
            "WHERE c.deleted = 0 AND c.status = 1 " +
            "AND (c.name LIKE CONCAT('%', #{keyword}, '%') " +
            "OR c.description LIKE CONCAT('%', #{keyword}, '%')) " +
            "ORDER BY c.document_count DESC, c.create_time DESC " +
            "LIMIT #{limit}")
    List<DocumentCategoryVO> searchCategories(@Param("keyword") String keyword,
                                             @Param("limit") Integer limit);

    /**
     * 获取热门分类
     * 
     * @param limit 限制数量
     * @return 分类列表
     */
    @Select("SELECT c.*, u.real_name as creator_name " +
            "FROM document_category c " +
            "LEFT JOIN user u ON c.creator_id = u.id " +
            "WHERE c.deleted = 0 AND c.status = 1 " +
            "ORDER BY c.document_count DESC, c.create_time DESC " +
            "LIMIT #{limit}")
    List<DocumentCategoryVO> selectHotCategories(@Param("limit") Integer limit);

    /**
     * 获取用户创建的分类
     * 
     * @param creatorId 创建者ID
     * @param limit 限制数量
     * @return 分类列表
     */
    @Select("SELECT c.*, u.real_name as creator_name " +
            "FROM document_category c " +
            "LEFT JOIN user u ON c.creator_id = u.id " +
            "WHERE c.creator_id = #{creatorId} AND c.deleted = 0 " +
            "ORDER BY c.create_time DESC " +
            "LIMIT #{limit}")
    List<DocumentCategoryVO> selectUserCategories(@Param("creatorId") String creatorId,
                                                 @Param("limit") Integer limit);

    /**
     * 检查分类是否有子分类
     * 
     * @param categoryId 分类ID
     * @return 是否有子分类
     */
    @Select("SELECT COUNT(*) > 0 FROM document_category " +
            "WHERE parent_id = #{categoryId} AND deleted = 0")
    Boolean hasChildCategories(@Param("categoryId") String categoryId);

    /**
     * 检查分类是否有文档
     * 
     * @param categoryId 分类ID
     * @return 是否有文档
     */
    @Select("SELECT COUNT(*) > 0 FROM document " +
            "WHERE category_id = #{categoryId} AND deleted = 0")
    Boolean hasDocuments(@Param("categoryId") String categoryId);
}
